<!DOCTYPE html>
<html>
<head>
    <title>WebSocket测试</title>
    <meta charset="UTF-8">
</head>
<body>
<h3>WebSocket消息测试</h3>
<input type="text" id="messageInput" placeholder="请输入消息">
<button onclick="sendMessage()">发送</button>
<button onclick="closeConnection()">关闭连接</button>
<div id="messageContainer" style="margin-top: 20px; border: 1px solid #ccc; padding: 10px; height: 300px; overflow: auto;"></div>

<script>
    // 初始化WebSocket连接（注意协议：http对应ws，https对应wss）
    let ws = new WebSocket('ws://localhost:8080/ws');

    // 连接成功回调
    ws.onopen = function() {
        appendMessage("连接已建立");
    };

    // 接收消息回调
    ws.onmessage = function(event) {
        appendMessage("收到：" + event.data);
    };

    // 连接关闭回调
    ws.onclose = function() {
        appendMessage("连接已关闭");
    };

    // 发送消息
    function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();
        if (message && ws.readyState === WebSocket.OPEN) {
            ws.send(message);
            input.value = '';
        }
    }

    // 关闭连接
    function closeConnection() {
        if (ws.readyState === WebSocket.OPEN) {
            ws.close();
        }
    }

    // 显示消息到页面
    function appendMessage(text) {
        const container = document.getElementById('messageContainer');
        const div = document.createElement('div');
        div.textContent = new Date().toLocaleTimeString() + '：' + text;
        container.appendChild(div);
        container.scrollTop = container.scrollHeight; // 滚动到底部
    }
</script>
</body>
</html>